package com.woniuxy.rabbit.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author ：yolo
 * @date ：Created in 2025/7/4 16:59
 * @description：
 * @modified By：
 * @version: $
 */
@Configuration
@Slf4j
public class CallbackConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
   @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
        rabbitTemplate.setMandatory(true);
    }


    /**
     * 生产者到交换机：不管是否成功，都会执行这个方法 前提条件：
     * spring:
     *   rabbitmq:
     *     publisher-confirm-type: correlated
     * @param correlationData
     * @param b
     * @param s
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        byte[] body = correlationData.getReturnedMessage().getBody();
        String receivedExchange = correlationData.getReturnedMessage().getMessageProperties().getReceivedExchange();
        String receivedRoutingKey = correlationData.getReturnedMessage().getMessageProperties().getReceivedRoutingKey();

        if (b){
            log.info("消息发送成功:{}",new String(body),receivedExchange,receivedRoutingKey);
        }else {
            //1\把消息体、队列、交换机等消息保存起来，方便重发
            //2、重发消息（次数有上限：如10，时间有间隔：如上一次间隔的两倍）

            log.error("消息发送失败，原因：{}",s);
        }

    }

    /**
     * 交换机到队列 消息没有路由到队列，会执行这个方法
     * 前提条件：
     * spring:
     *     rabbitmq:
     *        publisher-returns: true
     * @param message
     * @param i
     * @param s
     * @param s1
     * @param s2
     */
    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
       log.error( "消息发送失败，原因：{}",s);
    }
}
